package com.leetcode;

import java.util.Stack;

/**
 * 32. 最长有效括号
 *
 * @author fuyong
 */
public class Solution32 {

    /**
     * 32. 最长有效括号
     *
     * @param s 括号字符串
     * @return
     */
    public int longestValidParentheses(String s) {
        int maxLen = 0;
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    maxLen = Math.max(maxLen, i - stack.peek());
                }
            }
        }
        return maxLen;
    }

    public static void main(String[] args) {
	    // write your code here
        String s = "(()";
        int len = new Solution32().longestValidParentheses(s);
        System.out.println(len);
    }
}
